# Qdrant向量数据库初始化脚本 (PowerShell版本)
# 用于创建WMS知识库集合和配置

Write-Host "🚀 初始化Qdrant向量数据库..." -ForegroundColor Green

# Qdrant服务地址
$QDRANT_URL = "http://localhost:6333"
$COLLECTION_NAME = "wms_knowledge"

# 等待Qdrant服务启动
Write-Host "⏳ 等待Qdrant服务启动..." -ForegroundColor Yellow
$maxRetries = 10
$retryCount = 0
do {
    try {
        $response = Invoke-RestMethod -Uri "$QDRANT_URL/collections" -Method Get
        break
    }
    catch {
        $retryCount++
        Write-Host "等待Qdrant服务启动... ($retryCount/$maxRetries)" -ForegroundColor Yellow
        Start-Sleep -Seconds 2
    }
} while ($retryCount -lt $maxRetries)

Write-Host "✅ Qdrant服务已启动" -ForegroundColor Green

# 检查集合是否存在
Write-Host "🔍 检查集合是否存在..." -ForegroundColor Yellow
try {
    $collectionResponse = Invoke-RestMethod -Uri "$QDRANT_URL/collections/$COLLECTION_NAME" -Method Get
    Write-Host "✅ 集合 $COLLECTION_NAME 已存在" -ForegroundColor Green
}
catch {
    Write-Host "📝 创建集合 $COLLECTION_NAME..." -ForegroundColor Yellow
    
    # 创建集合的请求体
    $createCollectionBody = @{
        vectors = @{
            size = 384
            distance = "Cosine"
        }
        optimizers_config = @{
            default_segment_number = 2
        }
        replication_factor = 1
    } | ConvertTo-Json -Depth 10
    
    try {
        $response = Invoke-RestMethod -Uri "$QDRANT_URL/collections/$COLLECTION_NAME" -Method Put -Body $createCollectionBody -ContentType "application/json"
        Write-Host "✅ 集合 $COLLECTION_NAME 创建成功" -ForegroundColor Green
    }
    catch {
        Write-Host "❌ 集合创建失败: $($_.Exception.Message)" -ForegroundColor Red
        exit 1
    }
}

# 创建索引（可选）
Write-Host "📊 创建索引..." -ForegroundColor Yellow
try {
    $indexBody = @{
        field_name = "knowledge_id"
        field_schema = "integer"
    } | ConvertTo-Json
    
    Invoke-RestMethod -Uri "$QDRANT_URL/collections/$COLLECTION_NAME/index" -Method Put -Body $indexBody -ContentType "application/json"
    Write-Host "✅ 索引创建成功" -ForegroundColor Green
}
catch {
    Write-Host "⚠️ 索引创建失败（可能已存在）: $($_.Exception.Message)" -ForegroundColor Yellow
}

# 显示集合信息
Write-Host "📋 集合信息：" -ForegroundColor Cyan
try {
    $collectionInfo = Invoke-RestMethod -Uri "$QDRANT_URL/collections/$COLLECTION_NAME" -Method Get
    $collectionInfo | ConvertTo-Json -Depth 10 | Write-Host
}
catch {
    Write-Host "无法获取集合信息" -ForegroundColor Red
}

Write-Host "🎉 Qdrant向量数据库初始化完成！" -ForegroundColor Green
Write-Host ""
Write-Host "📝 使用说明：" -ForegroundColor Cyan
Write-Host "1. 集合名称: $COLLECTION_NAME"
Write-Host "2. 向量维度: 384 (OpenAI text-embedding-ada-002)"
Write-Host "3. 距离算法: Cosine"
Write-Host "4. API地址: $QDRANT_URL"
Write-Host ""
Write-Host "🔧 测试连接：" -ForegroundColor Cyan
Write-Host "Invoke-RestMethod -Uri '$QDRANT_URL/collections/$COLLECTION_NAME'"
